import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import React, { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'
import { io } from 'socket.io-client'
import { getTokenInfo } from '@/utils/storage'
import { getUser } from '@/store/actions/profile'

export default function Chat() {
  const [messageList, setMessageList] = useState([
    // 放两条初始消息
    { type: 'robot', text: '亲爱的用户您好，小智同学为您服务。' },
    { type: 'user', text: '你好' },
  ])
  const dispatch = useDispatch()
  // 输入框内容
  const [msg, setMsg] = useState('')
  // 当前用户信息
  const user = useSelector((state) => state.profile.user)
  const clientRef = useRef(null)
  const listRef = useRef(null)

  useEffect(() => {
    // 获取用户信息
    dispatch(getUser())

    // 创建客户端实例
    const client = io('http://geek.itheima.net', {
      transports: ['websocket'],
      // 在查询字符串参数中传递 token
      query: {
        token: getTokenInfo().token,
      },
    })

    // 将客户端实例缓存到 ref 引用中
    clientRef.current = client

    // 监听连接成功的事件
    client.on('connect', () => {
      // 向聊天记录添加消息
      setMessageList((messageList) => {
        return [
          ...messageList,
          { type: 'robot', text: '我现在恭候着您的提问。' },
        ]
      })
    })

    // 监听收到消息的事件
    client.on('message', (data) => {
      console.log('>>>>收到 socket.io 消息:', data)
      setMessageList((messageList) => {
        return [...messageList, { type: 'robot', text: data.msg }]
      })
    })

    // 销毁组件时关闭socket连接
    return () => {
      client.close()
    }
  }, [dispatch])

  // 滚动条
  useEffect(() => {
    // 根据messagelist更新变动进行滚动
    listRef.current.scrollTop =
      listRef.current.scrollHeight - listRef.current.offsetHeight
  }, [messageList])
  // 回车发消息
  const onSendMsg = (e) => {
    if (e.keyCode === 13) {
      // 向客户端发送消息
      clientRef.current.emit('message', {
        msg,
        timestamp: Date.now(),
      })

      // 向聊天记录中添加消息
      setMessageList((messageList) => [
        ...messageList,
        { type: 'user', text: msg },
      ])

      setMsg('')
    }
  }

  return (
    <div className={styles.root}>
      <NavBar className="fixed-header">小智同学</NavBar>

      {/* 聊天列表 */}
      <div className="chat-list" ref={listRef}>
        {messageList.map((item, index) => {
          if (item.type === 'robot') {
            //   机器人
            return (
              <div className="chat-item" key={index}>
                <img
                  src={'http://geek.itheima.net/images/user_head.jpg'}
                  alt=""
                />
                <div className="message">{item.text}</div>
              </div>
            )
          } else {
            // 用户
            return (
              <div className="chat-item user" key={index}>
                <img
                  src={
                    user.photo || 'http://geek.itheima.net/images/user_head.jpg'
                  }
                  alt=""
                />
                <div className="message">{item.text}</div>
              </div>
            )
          }
        })}

        {/* 底部输入框 */}
        <div className="input-footer">
          <Input
            placeholder="请描述您的问题"
            className="no-border"
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
            onKeyUp={onSendMsg}
          />
          <Icon type="iconbianji" />
        </div>
      </div>
    </div>
  )
}
